import * as vscode from "vscode";
import { translate } from "./baidu-translate";

// TODO6：完善打开新的弹窗面板命令
// 展示抽取文案的Webview
export const showWebView = (word: string, fromFile: string) => {
  return new Promise(async (resolve) => {
    // const panel = vscode.window.createWebviewPanel(
    //   "formPanel",
    //   "kiwi文案抽取",
    //   vscode.ViewColumn.One,
    //   {
    //     // 在webview中启用脚本
    //     enableScripts: true,
    //     // 隐藏时保留Webview上下文
    //     retainContextWhenHidden: true,
    //   }
    // );

    let en = "";

    try {
      en = await translate(word);
    } catch (e: any) {
      vscode.window.showErrorMessage("获取默认翻译时出错", e.message);
    }

    // panel.webview.html = getFormHtml(word, en, fromFile);

    // panel.webview.onDidReceiveMessage(async (message: any) => {
    //   if (message.type === "submit") {
    //     const formData = message.data;
    //     const { key, en } = formData;
    //     if (!key || !en) {
    //       vscode.window.showErrorMessage("请填写 key 和英文翻译");
    //       return;
    //     }

    //     panel.dispose();
    //     resolve(formData);
    //   }
    // });
  });
};

function getFormHtml(word: string, en: string, fromFile: string) {
  // 构建表单页面的 HTML
  return `
    <html>
      <head>
        <style>
          .form-input {
            width: 500px;
          }

          .tip {
            color: red;
          }
        </style>
      </head>
      <body>
        <h1>kiwi 中文文案抽取和翻译</h1>
        <form id="myForm">
          <span>中文文案：${word}</span><br><br>
          <span>来源文件：${fromFile}</span><br><br>
          <label for="key"><span class="tip">*</span>文案 key：</label>
          <input class="form-input" type="text" id="key" name="key" value="I18N."> 
          &nbsp; <span class="tip">*请注意填写</span> 
          <br><br>
          <label for="en"><span class="tip">*</span>英文翻译：</label>
          <input class="form-input" type="text" id="en" name="en" value="${en}"><br><br>
          <input type="submit" value="提交">
        </form>
        <script>
          const vscode = acquireVsCodeApi();
          const form = document.getElementById('myForm');
          form.addEventListener('submit', (event) => {
            event.preventDefault();
            const formData = new FormData(form);
            vscode.postMessage({
              type: 'submit',
              data: Object.fromEntries(formData),
            });
          });
        </script>
      </body>
    </html>
  `;
}
